package com.openecommerce.core.util;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 字符串处理工具类
 * @author Tommy
 *
 */
public class StringUtils {
	
	private static final Logger logger = LoggerFactory.getLogger(StringUtils.class);
	
	/**
	 * 用于实体类的toString方法
	 * @param object
	 * @return
	 */
	public static String objectToString(Object object){
		Method[]  methods = object.getClass().getMethods();
		List<Method> methodList = Arrays.asList(methods);
		StringBuilder sb = new StringBuilder();
		sb.append("{ ");
		for(Method method : methodList){
			if(method.getName().startsWith("get")){
				String fieldName = method.getName().substring(3);
				fieldName = fieldName.substring(0, 1).toLowerCase() + fieldName.substring(1);
				Object fieldValue;
				try {
					fieldValue = method.invoke(object);
				} catch (Exception e) {
					logger.error("父类获取子类数据异常", e);
					fieldValue = "null";
				}
				sb.append("'").append(fieldName).append("':").append(fieldValue == null? "null":fieldValue.toString()).append(",");
			}
		}
		if(sb.length() > 2){
			sb.deleteCharAt(sb.length()-1);
		}
		sb.append(" }");
		return sb.toString();
	}
}
